﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;

namespace Eaglight.Behaviors
{
    public class DisplayCoordinatesBehavior : Behavior<Map>
    {
        public DependencyProperty TargetProperty = DependencyProperty.Register("Target", typeof(TextBlock), typeof(DisplayCoordinatesBehavior), null);

        protected override void OnAttached()
        {
            AssociatedObject.MouseMove += new MouseEventHandler(AssociatedObject_MouseMove);
            AssociatedObject.MouseEnter += new MouseEventHandler(AssociatedObject_MouseEnter);
            AssociatedObject.MouseLeave += new MouseEventHandler(AssociatedObject_MouseLeave);
        }

        void AssociatedObject_MouseLeave(object sender, MouseEventArgs e)
        {
            Target.Visibility = Visibility.Collapsed;
        }

        void AssociatedObject_MouseEnter(object sender, MouseEventArgs e)
        {
            Target.Visibility = Visibility.Visible;
        }

        private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
        {
            Point p = e.GetPosition(AssociatedObject);
            MapPoint mp = AssociatedObject.ScreenToMap(p);
            if (mp != null)
            {
                Target.Text = string.Format("{0}, {1}", mp.X, mp.Y);
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter;
            AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
            AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave;
            
        }

        public TextBlock Target
        {
            get { return (TextBlock)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
            
        }
    }
}
